<?php
/**
 * 地区 模块服务
 *
 */

namespace Usap\Service\CMS;

use Think\Cache;

class location
{

    public function __construct()
    {

    }

    /**
     * 根据 part_id 获取对应的城市信息
     *
     * @param $part_id
     * @param bool $is_cache
     * @return array
     */
    public function getCityByPartId($part_id, $is_cache = true)
    {
        if($is_cache){
            $cache_info = $this->setCacheByPartId($part_id);
            if($cache_info){ return $cache_info; }
        }

        $city_info = D('Usap/Admin/LocationInfo')->getCityByPartId($part_id);
        if(empty($city_info)){ return array(); }
        !$is_cache ?: $this->setCacheByPartId($part_id, $city_info);

        return $city_info;
    }


    /**
     * 缓存设置
     *
     * @param $cache_key  缓存标识key
     * @param string $cache_info  缓存数据
     * @param int $expire_time  过期时间 默认为 1天
     * @return array
     */
    public function setCacheByPartId($cache_key, $cache_info = '', $expire_time = 86400)
    {
        if(empty($cache_key)){ return array(); }

        $cache_obj = Cache::singleton('redis');
        $key = "location:{$cache_key}";

        $cache_res = $cache_info ? $cache_obj->set($key, $cache_info, $expire_time) : $cache_obj->get($key);

        return $cache_res;
    }

    /**
     * 缓存 清除
     *
     * @param string $cache_key  缓存标识key
     * @return int
     */
    public function clearCacheByPartId($cache_key = '')
    {
        if($cache_key){ return 0; }

        $key_list = array();
        $key = "location:{$cache_key}:*";
        $cache_obj = Cache::singleton('redis');
        $res = $cache_obj->del($key);
        $key_list[] = $res;

//        $key_list = $cache_obj->keys($key);
//        if($key_list){
//            foreach ($key_list  as $key) {
//                $cache_obj->del($key);
//            }
//        }

        return is_array($key_list) ? count($key_list) : 0;
    }
}